<!--
 * @Author: wangzhichiao<https://github.com/wzc570738205>
 * @Date: 2020-11-03 17:46:23
 * @LastEditors: wangzhichiao<https://github.com/wzc570738205>
 * @LastEditTime: 2020-11-05 10:46:11
-->
<template>
  <div>
    <el-upload
      class="form-uploader"
      :action="`${$baseUrl}`"
      :show-file-list="true"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :limit="1"
    >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
  </div>
</template>

<script>
export default {
  name: 'UploadImg',
  props: {
    videoList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data: () => {
    return {
      fileList: [],
      playTime: 0
    }
  },
  mounted() {
    this.fileList = this.videoList
  },
  methods: {
    beforeUpload(file) {
      this.playTime = 0
      const isVideo = file.type === 'video/mp4'
      const isLt50M = file.size / 1024 / 1024 < 50
      const url = URL.createObjectURL(file)
      var audioElement = new Audio(url)
      audioElement.addEventListener('loadedmetadata', () => {
        this.playTime = audioElement.duration || 0 // playTime就是当前视频长度
      })
      if (!isVideo) {
        this.$message.error('上传视频只能是 mp4 格式!')
      }
      if (!isLt50M) {
        this.$message.error('上传视频大小不能超过 50MB!')
      }
      return isVideo && isLt50M
    },
    handleSuccess(res, file) {
      this.$message.success('视频上传成功')
      this.$attrs['handle-success-video'] && this.$attrs['handle-success-video'](res, this.playTime)
    }
  }
}
</script>

<style lang="scss" scoped>
.form-uploader {
  width: 200px;
}
</style>
